package com.pozu.new_retail.service.impl;

import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.pozu.new_retail.dao.mapper.ShareInfoMapper;
import com.pozu.new_retail.dao.mapper.ShareRecordMapper;
import com.pozu.new_retail.dao.model.ShareInfo;
import com.pozu.new_retail.dao.vo.BriefShareInfoVo;
import com.pozu.new_retail.dao.vo.ShareInfoVo;
import com.pozu.new_retail.dao.vo.ShareLinkedVo;
import com.pozu.new_retail.service.ShareInfoService;
import com.pozu.new_retail.utils.Constants;

@Service("shareInfoService")
public class ShareInfoServiceImpl implements ShareInfoService {

	@Autowired
	private ShareInfoMapper shareInfoMapper;
	@Autowired
	private ShareRecordMapper shareRecordMapper;
	
	@Override
	public ShareInfo queryByMap(HashMap<String, Object> hashMap) {
		return shareInfoMapper.queryByMap(hashMap);
	}

	@Override
	public long saveShareInfo(ShareInfo shareInfo) {
		
		long time = System.currentTimeMillis();
		
		shareInfo.setCreatedTime(time);
		shareInfo.setUpdatedTime(time);
		
		shareInfoMapper.insertShareInfo(shareInfo);
		
		return shareInfo.getShareId();
	}

	@Override
	public int updateShareInfo(ShareInfo shareInfo) {
		shareInfo.setUpdatedTime(System.currentTimeMillis());
		return shareInfoMapper.updateShareInfo(shareInfo);
	}

	@Override
	public ShareInfo queryByShareId(long shareId) {
		return shareInfoMapper.queryByShareId(shareId);
	}

	@Override
	public List<BriefShareInfoVo> queryListByUserId(HashMap<String, Object> map) {
		return shareInfoMapper.queryListByUserId(map);
	}

	@Override
	public ShareInfoVo queryDetailsByShareId(long shareId) {
		
		ShareInfoVo vo = shareInfoMapper.queryDetailsByShareId(shareId);
	
		long time = Constants.SHAREDLIMITTIME-(System.currentTimeMillis()-vo.getCreatedTime());
		
		if (time <= 0) {
			//失效
			ShareInfo shareInfo = new ShareInfo();
			shareInfo.setShareId(shareId);
			shareInfo.setState(1);
			updateShareInfo(shareInfo);
			vo.setState(1);
			vo.setTime(0L);
		}else {
			vo.setTime(time);
		}
		
		vo.setUserInfos(shareRecordMapper.queryByShareId(shareId));
		
		return vo;
	}

	@Override
	public ShareLinkedVo queryLinkedByShareId(long userId,long shareId) {
		
		ShareLinkedVo vo = shareInfoMapper.queryLinkedByShareId(shareId);
		long time = Constants.SHAREDLIMITTIME-(System.currentTimeMillis()-vo.getCreatedTime());
		
		if (time <= 0) {
			//失效
			ShareInfo shareInfo = new ShareInfo();
			shareInfo.setShareId(shareId);
			shareInfo.setState(1);
			updateShareInfo(shareInfo);
			vo.setState(1);
			vo.setTime(0L);
		}else {
			vo.setTime(time);
		}
		
		HashMap<String, Object> map = new HashMap<String,Object>();
		map.put("shareId", shareId);
		map.put("userId", userId);
		
		vo.setSharedFlag(shareRecordMapper.queryByMap(map) == null ? false : true);
		
		return vo;
	}

}
